<?php
/**
 * WordPress主题模板语法检查系统
 * WordPress Theme Template Syntax Checker System
 * 
 * @package WP Bootstrap Woo
 * @version 1.0.0
 */

if (!defined('ABSPATH')) {
    exit; // 禁止直接访问
}

/**
 * 语法检查核心控制器类
 * Core Syntax Checker Controller Class
 */
class WBW_Syntax_Checker {
    
    /**
     * 检查结果
     */
    private $check_results = array();
    
    /**
     * 错误信息
     */
    private $errors = array();
    
    /**
     * 警告信息
     */
    private $warnings = array();
    
    /**
     * 优化建议
     */
    private $optimization_suggestions = array();
    
    /**
     * 检查选项
     */
    private $check_options = array(
        'auto_fix' => false,
        'create_backup' => true,
        'check_performance' => true,
        'check_security' => true,
        'detailed_report' => true
    );
    
    /**
     * 文件扫描器
     */
    private $file_scanner;
    
    /**
     * 构造函数
     */
    public function __construct() {
        $this->init_file_scanner();
        $this->init_hooks();
    }
    
    /**
     * 初始化文件扫描器
     */
    private function init_file_scanner() {
        require_once get_template_directory() . '/inc/template-file-scanner.php';
        $this->file_scanner = new WBW_Template_File_Scanner();
    }
    
    /**
     * 初始化钩子
     */
    private function init_hooks() {
        if (current_user_can('manage_options')) {
            add_action('wp_ajax_wbw_run_syntax_check', array($this, 'ajax_run_syntax_check'));
            add_action('wp_ajax_wbw_check_performance', array($this, 'ajax_check_performance'));
            add_action('wp_ajax_wbw_auto_fix_syntax', array($this, 'ajax_auto_fix_syntax'));
            add_action('wp_ajax_wbw_get_check_history', array($this, 'ajax_get_check_history'));
        }
    }
    
    /**
     * 运行完整语法检查
     * 
     * @param array $options 检查选项
     * @return array 检查结果
     */
    public function run_complete_check($options = array()) {
        $this->check_options = array_merge($this->check_options, $options);
        $this->reset_results();
        
        // 开始检查流程
        $this->log_check_start();
        
        try {
            // 1. 扫描模板文件
            $this->check_template_files();
            
            // 2. 检查WooCommerce模板
            $this->check_woocommerce_templates();
            
            // 3. 检查性能配置
            if ($this->check_options['check_performance']) {
                $this->check_performance_settings();
            }
            
            // 4. 检查安全配置
            if ($this->check_options['check_security']) {
                $this->check_security_settings();
            }
            
            // 5. 生成优化建议
            $this->generate_optimization_suggestions();
            
            // 6. 自动修复（如果启用）
            if ($this->check_options['auto_fix']) {
                $this->auto_fix_issues();
            }
            
        } catch (Exception $e) {
            $this->add_error('检查过程中发生异常: ' . $e->getMessage());
        }
        
        $this->log_check_complete();
        
        return $this->get_results();
    }
    
    /**
     * 检查模板文件语法
     */
    private function check_template_files() {
        $this->add_section('模板文件语法检查');
        
        $template_files = $this->file_scanner->get_template_files();
        
        foreach ($template_files as $file_info) {
            $file_path = $file_info['path'];
            $file_name = $file_info['name'];
            $file_type = $file_info['type'];
            
            // 检查文件是否存在
            if (!file_exists($file_path)) {
                $this->add_result("❌ {$file_name} 文件不存在", 'error', $file_path);
                continue;
            }
            
            $this->add_result("✅ {$file_name} 文件存在", 'success', $file_path);
            
            // 执行语法检查
            $syntax_result = $this->check_php_syntax($file_path);
            
            if ($syntax_result['status'] === 'success') {
                $this->add_result("✅ {$file_name} 语法正确", 'success', $file_path);
            } else {
                $this->add_result("❌ {$file_name} 语法错误: {$syntax_result['message']}", 'error', $file_path);
                $this->add_error_detail($file_path, $syntax_result);
            }
            
            // 检查文件依赖
            $this->check_file_dependencies($file_path, $file_name);
        }
    }
    
    /**
     * 检查WooCommerce模板
     */
    private function check_woocommerce_templates() {
        if (!class_exists('WooCommerce')) {
            $this->add_result("ℹ️ WooCommerce未安装，跳过相关检查", 'info');
            return;
        }
        
        $this->add_section('WooCommerce模板检查');
        
        $woo_templates = $this->file_scanner->get_woocommerce_templates();
        
        foreach ($woo_templates as $template_info) {
            $file_path = $template_info['path'];
            $template_name = $template_info['name'];
            
            if (file_exists($file_path)) {
                $this->add_result("✅ {$template_name} 存在", 'success', $file_path);
                
                $syntax_result = $this->check_php_syntax($file_path);
                if ($syntax_result['status'] === 'success') {
                    $this->add_result("✅ {$template_name} 语法正确", 'success', $file_path);
                } else {
                    $this->add_result("❌ {$template_name} 语法错误", 'error', $file_path);
                    $this->add_error_detail($file_path, $syntax_result);
                }
                
                // 检查WooCommerce模板版本兼容性
                $this->check_woo_template_version($file_path, $template_name);
                
            } else {
                $this->add_result("⚠️ {$template_name} 使用默认模板", 'warning', $file_path);
            }
        }
    }
    
    /**
     * 检查性能配置
     */
    private function check_performance_settings() {
        $this->add_section('性能优化检查');
        
        // 检查CSS优化设置
        $css_optimize = _xin('optimize_css', false);
        if ($css_optimize) {
            $this->add_result('✅ CSS优化已启用', 'success');
        } else {
            $this->add_result('⚠️ CSS优化未启用', 'warning');
            $this->add_optimization_suggestion('css_optimize');
        }
        
        // 检查JavaScript优化设置
        $js_optimize = _xin('optimize_js', false);
        if ($js_optimize) {
            $this->add_result('✅ JavaScript优化已启用', 'success');
        } else {
            $this->add_result('⚠️ JavaScript优化未启用', 'warning');
            $this->add_optimization_suggestion('js_optimize');
        }
        
        // 检查图片懒加载
        $lazy_load = _xin('lazy_load_images', false);
        if ($lazy_load) {
            $this->add_result('✅ 图片懒加载已启用', 'success');
        } else {
            $this->add_result('⚠️ 图片懒加载未启用', 'warning');
            $this->add_optimization_suggestion('lazy_load');
        }
        
        // 检查CDN配置
        $cdn_mode = _xin('assets_cdn_mod', 'theme');
        if ($cdn_mode !== 'theme') {
            $this->add_result('✅ CDN加速已启用', 'success');
        } else {
            $this->add_result('⚠️ CDN加速未启用', 'warning');
            $this->add_optimization_suggestion('cdn_config');
        }
        
        // 检查缓存配置
        $this->check_cache_settings();
        
        // 检查资源加载策略
        $this->check_resource_loading_strategy();
    }
    
    /**
     * 检查安全配置
     */
    private function check_security_settings() {
        $this->add_section('安全配置检查');
        
        // 检查文件权限
        $this->check_file_permissions();
        
        // 检查敏感文件访问
        $this->check_sensitive_files();
        
        // 检查代码注入风险
        $this->check_code_injection_risks();
    }
    
    /**
     * PHP语法检查
     * 
     * @param string $file_path 文件路径
     * @return array 检查结果
     */
    private function check_php_syntax($file_path) {
        if (!file_exists($file_path)) {
            return array(
                'status' => 'error',
                'message' => '文件不存在',
                'line' => 0
            );
        }
        
        // 使用PHP内置语法检查
        $output = array();
        $return_var = 0;
        
        // 构建命令
        $command = "php -l " . escapeshellarg($file_path) . " 2>&1";
        exec($command, $output, $return_var);
        
        if ($return_var === 0) {
            return array(
                'status' => 'success',
                'message' => '语法正确'
            );
        } else {
            $error_message = implode("\n", $output);
            $error_line = $this->extract_error_line($output);
            
            return array(
                'status' => 'error',
                'message' => $error_message,
                'line' => $error_line,
                'suggestions' => $this->get_syntax_fix_suggestions($error_message)
            );
        }
    }
    
    /**
     * 提取错误行号
     * 
     * @param array $output 命令输出
     * @return int 行号
     */
    private function extract_error_line($output) {
        foreach ($output as $line) {
            if (preg_match('/on line (\d+)/', $line, $matches)) {
                return intval($matches[1]);
            }
        }
        return 0;
    }
    
    /**
     * 获取语法修复建议
     * 
     * @param string $error_message 错误信息
     * @return array 修复建议
     */
    private function get_syntax_fix_suggestions($error_message) {
        $suggestions = array();
        
        if (strpos($error_message, 'unexpected') !== false) {
            $suggestions[] = '检查括号、引号是否正确匹配';
            $suggestions[] = '检查语句是否缺少分号';
        }
        
        if (strpos($error_message, 'Parse error') !== false) {
            $suggestions[] = '检查PHP语法是否正确';
            $suggestions[] = '检查变量名是否有效';
        }
        
        if (strpos($error_message, 'undefined') !== false) {
            $suggestions[] = '检查变量是否已定义';
            $suggestions[] = '检查函数是否存在';
        }
        
        return $suggestions;
    }
    
    /**
     * 检查文件依赖
     * 
     * @param string $file_path 文件路径
     * @param string $file_name 文件名
     */
    private function check_file_dependencies($file_path, $file_name) {
        $content = file_get_contents($file_path);
        
        // 检查require/include语句
        $pattern = '/(?:require_once|require|include_once|include)\s*\(?\s*[\'"]([^\'"]+)[\'"]\s*\)?/';
        preg_match_all($pattern, $content, $matches);
        
        foreach ($matches[1] as $dependency) {
            $dep_path = $this->resolve_dependency_path($dependency, $file_path);
            if ($dep_path && !file_exists($dep_path)) {
                $this->add_result("⚠️ {$file_name} 依赖文件缺失: {$dependency}", 'warning', $file_path);
            }
        }
    }
    
    /**
     * 解析依赖文件路径
     * 
     * @param string $dependency 依赖路径
     * @param string $current_file 当前文件路径
     * @return string|false 绝对路径
     */
    private function resolve_dependency_path($dependency, $current_file) {
        // 处理相对路径
        if (strpos($dependency, '/') === 0) {
            return ABSPATH . ltrim($dependency, '/');
        }
        
        if (strpos($dependency, './') === 0) {
            return dirname($current_file) . '/' . substr($dependency, 2);
        }
        
        if (strpos($dependency, '../') === 0) {
            return dirname($current_file) . '/' . $dependency;
        }
        
        // WordPress函数路径
        if (strpos($dependency, 'get_template_directory') !== false) {
            // 这些需要运行时解析，暂时跳过
            return false;
        }
        
        return dirname($current_file) . '/' . $dependency;
    }
    
    /**
     * 添加检查结果
     * 
     * @param string $message 消息
     * @param string $type 类型 (success, error, warning, info)
     * @param string $file_path 文件路径 (可选)
     */
    private function add_result($message, $type = 'info', $file_path = '') {
        $this->check_results[] = array(
            'message' => $message,
            'type' => $type,
            'file_path' => $file_path,
            'timestamp' => current_time('timestamp')
        );
        
        if ($type === 'error') {
            $this->errors[] = $message;
        } elseif ($type === 'warning') {
            $this->warnings[] = $message;
        }
    }
    
    /**
     * 添加检查节
     * 
     * @param string $title 节标题
     */
    private function add_section($title) {
        $this->check_results[] = array(
            'type' => 'section',
            'title' => $title,
            'timestamp' => current_time('timestamp')
        );
    }
    
    /**
     * 重置检查结果
     */
    private function reset_results() {
        $this->check_results = array();
        $this->errors = array();
        $this->warnings = array();
        $this->optimization_suggestions = array();
    }
    
    /**
     * 获取检查结果
     * 
     * @return array 完整的检查结果
     */
    public function get_results() {
        return array(
            'summary' => array(
                'total_checks' => count($this->check_results),
                'errors' => count($this->errors),
                'warnings' => count($this->warnings),
                'success_rate' => $this->calculate_success_rate()
            ),
            'results' => $this->check_results,
            'errors' => $this->errors,
            'warnings' => $this->warnings,
            'optimization_suggestions' => $this->optimization_suggestions,
            'timestamp' => current_time('timestamp')
        );
    }
    
    /**
     * 计算成功率
     * 
     * @return float 成功率百分比
     */
    private function calculate_success_rate() {
        $total = count($this->check_results);
        if ($total === 0) return 100.0;
        
        $errors = count($this->errors);
        return round((($total - $errors) / $total) * 100, 2);
    }
    
    /**
     * Ajax处理语法检查
     */
    public function ajax_run_syntax_check() {
        if (!wp_verify_nonce($_POST['nonce'], 'wbw_syntax_check_nonce')) {
            wp_send_json_error('安全验证失败');
        }
        
        $check_type = sanitize_text_field($_POST['check_type'] ?? 'all');
        $auto_fix = isset($_POST['auto_fix']) && $_POST['auto_fix'] === 'true';
        
        $options = array(
            'auto_fix' => $auto_fix,
            'check_performance' => $check_type === 'all' || $check_type === 'performance',
            'detailed_report' => true
        );
        
        $results = $this->run_complete_check($options);
        
        wp_send_json_success($results);
    }
    
    /**
     * 记录检查开始
     */
    private function log_check_start() {
        $this->log_message('语法检查开始', 'info');
    }
    
    /**
     * 记录检查完成
     */
    private function log_check_complete() {
        $summary = $this->get_results()['summary'];
        $message = sprintf(
            '语法检查完成 - 总计: %d, 错误: %d, 警告: %d, 成功率: %.2f%%',
            $summary['total_checks'],
            $summary['errors'], 
            $summary['warnings'],
            $summary['success_rate']
        );
        $this->log_message($message, 'info');
    }
    
    /**
     * 记录日志消息
     * 
     * @param string $message 消息
     * @param string $level 级别
     */
    private function log_message($message, $level = 'info') {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log("[WBW_Syntax_Checker] [{$level}] {$message}");
        }
    }
}